﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Text;
using System.Threading.Tasks;

namespace JNPF.Utils.Controller
{
    /// <summary>
    /// 错误异常（ApiController发生异常时会执行这里）
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// </summary>
    public class FilterException : ExceptionFilterAttribute
    {
        /// <summary>
        /// 异常处理方法
        /// </summary>
        /// <param name="context"></param>
        public override async Task OnExceptionAsync(ExceptionContext context)
        {
            context.ExceptionHandled = true;
            context.HttpContext.Response.StatusCode = 200;
            //if (context.Exception is Warning warning)
            //{正常返回

            //}
            //else { 错误返回

            //}
            context.Result = new JsonResult(new ResponseResult() { code = ResponseCode.Exception, msg = context.Exception.Message });
            await WriteLog(context);
        }

        #region 写入日志
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="context"></param>
        private async Task WriteLog(ExceptionContext context)
        {
            if (context == null)
                return;
            var httpContext = Utils.HttpContext.Current;
            var userProvider = new UserProvider();
            var strException = new StringBuilder();
            if (userProvider.IsOverdue != false && context.Exception.InnerException != null)
            {
                strException.Append("1. 请求: " + httpContext.Request.Path + "    \r\n");
                strException.Append("2. 类名: " + context.Exception.TargetSite.DeclaringType.FullName + " \r\n");
                strException.Append("3. 方法: " + context.Exception.TargetSite.Name + " \r\n");
                strException.Append("4. 异常: " + context.Exception + "\r\n");
                var userInfo = userProvider.Get();
                //写入数据库
                var entity = new LogEntity
                {
                    Category = LogSortEnum.Exception,
                    UserId = userInfo.UserId,
                    UserName = userInfo.UserName + "/" + userInfo.UserAccount,
                    RequestURL = httpContext.Request.Path,
                    RequestMethod = httpContext.Request.Method.ToString(),
                    Json = strException.ToString(),
                    IPAddress = Net.Ip
                };
                await LogBll.Instance.WriteLogAsync(entity);
            }
            else
            {
                strException.Append("1. 请求: " + httpContext.Request.Path + "    \r\n");
                strException.Append("2. 类名: " + context.Exception.TargetSite.DeclaringType.FullName + " \r\n");
                strException.Append("3. 方法: " + context.Exception.TargetSite.Name + " \r\n");
                strException.Append("4. 异常: " + context.Exception + "\r\n");
            }
            //写入日志
            LogFactory.GetLogger().Error(strException.ToString());
        }
        #endregion
    }
}